package com.kcnet.qk.controller;

import android.accessibilityservice.AccessibilityService;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;


import com.kcnet.qk.app.App;
import com.kcnet.qk.app.AppContext;
import com.kcnet.qk.constant.Const;
import com.kcnet.qk.controller.addfriend.AddFriendAdoptCTR;
import com.kcnet.qk.service.AutoAddPeopleService;
import com.kcnet.qk.util.JsonNettyData;
import com.kcnet.qk.util.NodeUtil;
import com.kcnet.qk.util.PreferenceHelper;
import com.kcnet.qk.util.RootShell;
import com.kcnet.qk.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import static com.kcnet.qk.constant.Const.FbUI.*;
import static com.kcnet.qk.constant.Const.TEXT_VIEW;

import java.io.DataOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;


/**
 * Created by czc on 2017/7/29.
 */

public abstract class BasePeopleController {

    public int mType;
    public String mClassName;
    public boolean initFbMain;

    public int maxAddCount = 2; //最大添加10人
    public int currentAddCount = 0; //当前任务添加人数
    public int minAddTime = 1; //最小时间间隔
    public int maxAddTime = 3; //最大时间间隔

    protected static final String TAG = "czc";

    protected Object mLock = new Object();

    public int errMaxCount = 5;
    public int errCurrentCount = 0;

    private Random random = new Random();

    public AccessibilityNodeInfo getRoot() {
        return AppContext.getInstance().getmService().getRoot();
    }

    public void sleepTimedDefault() {
        try {
            int c = Random(minAddTime, maxAddTime) * 1000;
            Log.d(TAG,"sleepTimedDefault:"+c);
            Thread.sleep(c);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 睡眠
     *
     * @param millis
     */
    public void sleepTime(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void stopTask() {
        JsonNettyData.sendToServerFlag(AppContext.taskId,2,"执行完毕");
        AppContext.taskId = -1;
        AppContext.taskType = -1;
        AppContext.taskStartTime = -1;
        initFbMain = false;
        PreferenceHelper.putBoolean(Const.PREF_KEY_STOP_AUTO_FLAG, false);
        EventBus.getDefault().post(new Boolean(false));
        try {
            ToastUtil.showToast(AppContext.getInstance().getContext(), "任務執行完畢 停止任務");
        }catch (Exception e){

        }
        Log.i("czc", "停止任务 ");
    }


    public boolean searchTypeClick(String tag) {
        AccessibilityNodeInfo root = AppContext.getInstance().getmService().getRoot();
        if (root != null) {
            List<AccessibilityNodeInfo> nodeByClassList = NodeUtil.traverseNodeByClassList(root, TEXT_VIEW);

            for (int i = 0; i < nodeByClassList.size(); i++) {
                AccessibilityNodeInfo nodeInfo = nodeByClassList.get(i);
                Log.d("ND", "点击了gotoFriendType" + nodeInfo);
                if (nodeInfo.getText() != null && nodeInfo.getText().equals(tag)) {
                    Log.d("ND", "点击了gotoFriendType" + NodeUtil.performClick(nodeInfo));
                    return true;

                }
            }
        }
        return false;
    }

    /*
    * @Description:  根据 AccessibilityNodeInfo 获取 坐标 进行 shell点击
    * @Param: [tag] 
    * @return: void 
    * @Author: 赵浩
    * @Date: 2018-05-01 1:59 
    */
    public boolean Onclie_Shell_As(String tag, int z) {
        AccessibilityNodeInfo root = AppContext.getInstance().getmService().getRoot();
        if (root != null) {
            List<AccessibilityNodeInfo> nodeByClassList = NodeUtil.getTextByNodeView(root, tag);
            Log.d("ND", "Onclie_Shell_As 搜索点击 " + tag + " 数量：" + nodeByClassList.size());
            if ( z < nodeByClassList.size()) {
                for (int i = z ; i < nodeByClassList.size(); i++) {
                    AccessibilityNodeInfo nodeInfo = nodeByClassList.get(i);
                    AccessibilityNodeInfoCompat compat3 = new AccessibilityNodeInfoCompat(nodeInfo);
                    Rect outBounds3 = new Rect();
                    compat3.getBoundsInScreen(outBounds3);
                    outBounds3.centerX();
                    outBounds3.centerY();
                    Log.d("ND", "Onclie_Shell_As");
                    Log.d("ND", nodeInfo.toString());
                    RootShell.click(outBounds3.centerX(),outBounds3.centerY());
                  //  execShellCmd("input tap " + Integer.toString(outBounds3.centerX()) + " " + Integer.toString(outBounds3.centerY()));
                    return true;
                }
            }
        }
        Log.d("ND", "Onclie_Shell_As 未搜索到。");
        return false;
    }


//    public void tabPage2Click() {
//        AccessibilityNodeInfo root = AppContext.getInstance().getmService().getRoot();
//        if (root != null) {
//
//            List<AccessibilityNodeInfo> nodeByClassList = NodeUtil.getTextByNodeView(root, "加好友请求");
//            Log.d("ND", "nodeByClassList size:" + nodeByClassList.size());
//            for (int i = 0; i < nodeByClassList.size(); i++) {
//                AccessibilityNodeInfo nodeInfo = nodeByClassList.get(i);
//                NodeUtil.performClick(nodeInfo);
//                break;
//
//            }
//        }
//    }

    /**
     * 輸入文本框
     *
     * @param text
     */
    public void inputSayHiSentence(String text) {
        Log.i("czc", "inputSayHiSentence text："+text);
        //找到当前获取焦点的view
        AccessibilityNodeInfo root = getRoot();
        if (root != null) {
            AccessibilityNodeInfo target = root.findFocus(AccessibilityNodeInfo.FOCUS_INPUT);
            if (target != null && Build.VERSION.SDK_INT >= 21) {
                // if (mSentenceList != null && mSentenceList.size() > 0) {
                Random random = new Random();
                //   int nextInt = random.nextInt(mSentenceList.size());
                Bundle arguments = new Bundle();
                arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE,
                        text);
                target.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments);
                // }
            }
            //NodeUtil.findNodeByTextAndPerformClick(root, "发送");
        }
    }

    /*
    * @Description: 搜索文本点击
    * @Param: [tag] 
    * @return: void 
    * @Date: 2018-04-27 14:20
    */
    public boolean tagTextClick(String tag) {
        AccessibilityNodeInfo root = AppContext.getInstance().getmService().getRoot();
        if (root != null) {
            List<AccessibilityNodeInfo> nodeByClassList = NodeUtil.getTextByNodeView(root, tag);
            Log.d("搜索 - " + tag + " - 数量:", Integer.toString(nodeByClassList.size()));
            for (int i = 0; i < nodeByClassList.size(); i++) {
                AccessibilityNodeInfo nodeInfo = nodeByClassList.get(i);
                Log.d("ND", "点击了" + tag + NodeUtil.performClick(nodeInfo) + " size:" + nodeByClassList.size());
                return true;
            }
        }
        return false;

    }



    /*
    * @Description: 搜索文本点击
    * @Param: [tag]
    * @return: void
    * @Date: 2018-04-27 14:20
    */
    public AccessibilityNodeInfo findTextNodeInfo(String tag) {
        AccessibilityNodeInfo root = AppContext.getInstance().getmService().getRoot();
        if (root != null) {
            List<AccessibilityNodeInfo> nodeByClassList = NodeUtil.getTextByNodeView(root, tag);
            Log.d("搜索 - " + tag + " - 数量:", Integer.toString(nodeByClassList.size()));
            for (int i = 0; i < nodeByClassList.size(); i++) {
                AccessibilityNodeInfo nodeInfo = nodeByClassList.get(i);
                return nodeInfo;
            }
        }
        return null;

    }

    /*
    * @Description: 搜索文本点击
    * @Param: [tag]
    * @return: void
    * @Date: 2018-04-27 14:20
    */
    public boolean tagIdClick(String id) {
        AccessibilityNodeInfo root = AppContext.getInstance().getmService().getRoot();
        if (root != null) {
            List<AccessibilityNodeInfo> nodeByClassList = NodeUtil.getidByNodeView(root, id);
            Log.d("搜索 - " + id + " - 数量:", Integer.toString(nodeByClassList.size()));
            for (int i = 0; i < nodeByClassList.size(); i++) {
                AccessibilityNodeInfo nodeInfo = nodeByClassList.get(i);
                Log.d("ND", "点击了" + id + NodeUtil.performClick(nodeInfo) + " size:" + nodeByClassList.size());
                return true;
            }
        }
        return false;

    }

    /*
       * @Description: 搜索文本点击
       * @Param: [tag]
       * @return: void
       * @Date: 2018-04-27 14:20
       */
    public boolean findTextClick(String tag) {
        AccessibilityNodeInfo root = AppContext.getInstance().getmService().getRoot();
        if (root != null) {
            List<AccessibilityNodeInfo> nodeByClassList = NodeUtil.getTextByNodeView(root, tag);
            Log.d("搜索 - " + tag + " - 数量:", Integer.toString(nodeByClassList.size()));
            if (!nodeByClassList.isEmpty()) {
                return true;
            }
        }
        return false;

    }


    public boolean tagTextClickShell(AccessibilityNodeInfo AccessibilityNodeInfo){
        AccessibilityNodeInfo nodeInfo = AccessibilityNodeInfo;
        AccessibilityNodeInfoCompat compat3 = new AccessibilityNodeInfoCompat(nodeInfo);
        Rect outBounds3 = new Rect();
        compat3.getBoundsInScreen(outBounds3);
        int topX=outBounds3.width()/2;
        int topY=outBounds3.height()/2;

        int tx = outBounds3.centerX();
        int ty = outBounds3.centerY();
        Log.d("ND", "tagTextClickShell x:"+outBounds3.centerX()+" y:"+outBounds3.centerY()+" tx:"+tx+" ty:"+ty +" outBound TOP:"+ outBounds3.top+" left"+outBounds3.left);
        if (RootShell.click(tx,ty)){
            return true;
        }else {
            return  false;
        }


    }
    public boolean tagTextClickShell(String text){
        AccessibilityNodeInfo nodeInfo = findTextNodeInfo(text);
        if(nodeInfo==null){
            return false;
        }
        AccessibilityNodeInfoCompat compat3 = new AccessibilityNodeInfoCompat(nodeInfo);
        Rect outBounds3 = new Rect();
        compat3.getBoundsInScreen(outBounds3);
        outBounds3.centerX();
        outBounds3.centerY();
        Log.d("ND", "tagTextClickShell x:"+outBounds3.centerX()+" y:"+outBounds3.centerY());
        if (RootShell.click(outBounds3.centerX(),outBounds3.centerY())){
            return true;
        }else {
            return  false;
        }


    }
    /*
    * @Description: 在搜索文字的同时可以选择点击次数
    * @Param: [tag, z] 
    * @return: void 
    * @Author: 赵浩
    * @Date: 2018-04-28 15:39 
    */
    public boolean tagTextClick(String tag, int z) {
        AccessibilityNodeInfo root = AppContext.getInstance().getmService().getRoot();
        if (root != null) {
            List<AccessibilityNodeInfo> nodeByClassList = NodeUtil.getTextByNodeView(root, tag);
            Log.d("搜索 - " + tag + " - 数量:", Integer.toString(nodeByClassList.size()));
            if (nodeByClassList.size() == 0) {
                return false;
            }
            //如果选择的数量大于总数量，那么就重新赋值
            if (z > nodeByClassList.size()) {
                z = nodeByClassList.size();
            }
            for (int i = 0; i < z; i++) {
                AccessibilityNodeInfo nodeInfo = nodeByClassList.get(i);
//                Log.d("ND", "点击了" + tag + NodeUtil.performClick(nodeInfo) + " size:" + i);
                sleepTime(500);
                for (int j = 0; j < 10; j++) {
                    if (tagTextClickShell(nodeInfo)){
                        break;
                    }
                    sleepTime(1000);
                }


            }
            return true;
        }
        return false;
    }


    public void searchClick() {
        AccessibilityNodeInfo root = AppContext.getInstance().getmService().getRoot();
        if (root != null) {

            List<AccessibilityNodeInfo> nodeByClassList = NodeUtil.getTextByNodeView(root, "搜索好友");

            for (int i = 0; i < nodeByClassList.size(); i++) {
                AccessibilityNodeInfo nodeInfo = nodeByClassList.get(i);

                if (nodeInfo.getContentDescription() != null && nodeInfo.getContentDescription().equals("搜索好友")) {
                    Log.d("ND", "点击了gotoFriendType" + NodeUtil.performClick(nodeInfo) + " size:" + nodeByClassList.size());
                    break;

                }
            }
        }
    }



    /*
    * @Description:  生成简单的随机数
    * @Param: [min, max] 
    * @return: int 
    * @Author: 赵浩
    * @Date: 2018-05-01 3:23 
    */
    public int Random(int min, int max) {

        int s = random.nextInt(max)%(max-min+1) + min;
        return s;
    }



    /**
     * 全局返回事件
     */
    public boolean performBackClick() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
         return AppContext.getInstance().getmService().performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);

    }
    /**
     * 滑动下到上
     */
    public boolean SWIPE_DOWN_AND_UPClick() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return AppContext.getInstance().getmService().performGlobalAction(AccessibilityService.GESTURE_SWIPE_UP);
    }



    public abstract void doTask(AccessibilityEvent event)throws Exception;
}
